<?php
namespace App\Services\Order;

use App\Contracts\Order\OrderContracts;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use App\Models\MemberAddress;
use App\Models\Order;
use Illuminate\Support\Carbon;
use App\Models\ProductSku;

class OrderService implements OrderContracts
{
    public function store($address, $user, $remark, $items)
    {
        DB::beginTransaction();
        
        try{
            //更新收货地址时间
            if (!$address = $this->updateMemberAddressTime($address)){
                DB::rollback();
                return [
                    'code' => 400,
                    'error' =>  Config::get('error.order.address'),
                ];
            }

            // 先添加订单记录
            if (!$order = $this->orderSave($address,$remark,$user)){
                DB::rollback();
                return [
                    'code' => 400,
                    'error' =>  Config::get('error.order.order_save'),
                ];
            }

            // 添加订单详情 并且计算总价格
            if (!$total_amount = $this->orderItemSave($order,$items)){
                DB::rollback();
                return [
                    'code' => 400,
                    'error' =>  Config::get('error.order.order_items'),
                ];
            }

            //更新订单总价格
            $this->updateTotalAmount($order,$total_amount);

            if (!$this->RemoveCart($user,$items)){
                DB::rollback();
                return [
                    'code' => 400,
                    'error' =>  Config::get('error.order.cart'),
                ];
            }
        }
        catch(\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            return [
                'code' => 400,
                'error' =>  Config::get('error.err'),
            ];
        }

        

        DB::commit();
      
        // dispatch(new CloseOrder($order,3));
        return $order;
    }

    public function updateMemberAddressTime($addressId)
    {
        try{
            $address = MemberAddress::find($addressId);//先查询再修改是为了后面能够使用获取器功能

            $address->update([
                'last_used_at' => Carbon::now()//获取当前时间
            ]);
    
            return $address;
        }
        catch(\Illuminate\Database\QueryException $ex){
            return '报错了';
        }
        
    }

    /** 
    * @Description: 添加订单详情 并且计算总价格
    * @param: order 刚刚新建的订单详情
    * @param: skus arr 多规格数据
    * @return: total_amount int 总金额
    */     
    public function orderItemSave($order, $skus)
    {
        $total_amount = 0;

        foreach ($skus as $data){
            $sku = ProductSku::query()->find($data["sku_id"]);

            $item = $order->items()->make([
                'amount' => $data["amount"],
                'price' => $sku->price
            ]);

            $item->product()->associate($sku->product_id);
            $item->productSku()->associate($sku);
            $item->save();

            $total_amount += $sku->price *  $data["amount"];

            if ($sku->decreaseStock($data["amount"]) <= 0){
                throw  new \Exception("该商品库存不足");
            }
        }

        return $total_amount;
    }

    public function orderSave($address, $remark, $user)
    {
        $order = new Order([
            'address' => [
                'address' => $address->full_address,//模型获取器 对应 getFullAddressAttribute 方法
                'zip' => $address->zip,//邮编
                'contact_name' => $address->contact_name,
                'contact_phone' => $address->contact_phone
            ],
            'remark' => $remark,
            'total_amount' => 0
        ]);

        $order->user()->associate($user);

        $order->save();

        return $order;

    }

    public function updateTotalAmount($order, $total_amount)
    {
        // 使用的是 update而不是save
        return $order->update(['total_amount'=>$total_amount]);
    }

    // 清掉购物车
    public function RemoveCart($user, $sku)
    {
        // pluck 译为采和拔
        $skuIds = collect($sku)->pluck('sku_id')->all();//取到所有的规格id数组
        if (!is_array($skuIds)){
            $skuIds = [$skuIds];
        }

        $cart = $user->cartItems()->whereIn('product_sku_id',$skuIds)->delete();
        return $cart;
    }
}